package org.example.servlet_01.request;

import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Map;
import java.util.Set;

/**
 *  获取请求数据通用方法（消除post和get获取请求数据的差异）
 */

@WebServlet("/RequestDemo4")
public class RequestDemo4 extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //设置流的编码来解决post获得的请求数据中文乱码问题
        request.setCharacterEncoding("UTF-8");

        //1. 获取参数值
        String username = request.getParameter("username");
        System.out.println("username："+username);
        System.out.println("----------------------------------------");

        //2. 获取参数值(数组)
        String[] hobbies = request.getParameterValues("hobby");
        System.out.println("hobbys：");
        for (String hobby : hobbies) {
            System.out.print(hobby+' ');
        }
        System.out.println("\n----------------------------------------");

        //3. 获取所有参数名称再获取其值(一个)
        Enumeration<String> params = request.getParameterNames();
        while(params.hasMoreElements()){
            String name = params.nextElement();
            String value = request.getParameter(name);
            System.out.println(name + ":" + value);
        }
        System.out.println("----------------------------------------");

        //4.获取所有参数的map集合
        Map<String,String[]>parame = request.getParameterMap();
        //获取key
        Set<String> keySet = parame.keySet();
        //遍历key
        for (String key : keySet) {
            //遍历value
            String[] values = parame.get(key);
            for (String value : values) {
                System.out.println(key + ":" + value);
            }
        }
    }
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //this.doPost(request,response);
    }
}
